package freespiritsocial.io.user.ui.fragment.search

import android.os.Bundle
import androidx.core.os.bundleOf
import androidx.lifecycle.ViewModelStoreOwner
import com.scwang.smart.refresh.layout.util.SmartUtil.dp2px
import freespiritsocial.io.user.R
import freespiritsocial.io.user.base.BaseFragment
import freespiritsocial.io.user.databinding.FrgSearchPeopleBinding
import freespiritsocial.io.user.decoration.SpaceItemDecoration
import freespiritsocial.io.user.ext.init
import freespiritsocial.io.user.ui.adapter.search.PeopleAdapter
import freespiritsocial.io.user.ui.fragment.mine.MineFrg
import freespiritsocial.io.user.viewmodel.SearchViewModel
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.loge

/**
 * @description 搜索用户
 */
class SearchPeopleFrg: BaseFragment<SearchViewModel,FrgSearchPeopleBinding>() {
    companion object {
        fun crate(viewModelStore: ViewModelStoreOwner) =
            SearchPeopleFrg().apply {
                viewModelOwner = viewModelStore
            }

    }

    val adapter by lazy(LazyThreadSafetyMode.NONE) {
        PeopleAdapter(mViewModel).apply {
            setOnItemChildClickListener { adapter,view,position ->
                val pojo = data[position]
                mViewModel.getUserInfo(pojo.searchPeoplePojo?.userId) {
                    nav().navigateAction(R.id.action_mainFrg_to_mineFrg,bundleOf(MineFrg.KEY_IS_USER to false,MineFrg.KEY_USER to it))
                }
            }
            loadMoreModule.setOnLoadMoreListener {
                data.lastOrNull()?.searchPeoplePojo?.userId?.loge("csw")
                mViewModel.getSearchList(SearchViewModel.people,data.lastOrNull()?.searchPeoplePojo?.userId)
            }
        }
    }

    override fun layoutId(): Int = R.layout.frg_search_people

    override fun initView(savedInstanceState: Bundle?) = with(mDatabind) {
        recyclerView.init(adapter,emptyText = getString(R.string.search_empty_message),emptyImage = R.mipmap.empty_search).addItemDecoration(
            SpaceItemDecoration(0,dp2px(20f))
        )
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.searchIng.observe(this) {
            if (it) {
                adapter.data.clear()
                mViewModel.getSearchList(SearchViewModel.people)
            }
        }
        mViewModel.peopleResult.observe(this) {
            adapter.addData(it)
            adapter.loadMoreModule.loadMoreComplete()
            adapter.loadMoreModule.isEnableLoadMore = it.isNotEmpty()
        }
    }

    inner class Click
}